﻿using aier.dataaccess.dapper;
using aier.dataaccess.model;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace aier.business.logic
{
    public class SequenceBll
    {

        public ILog log { get; set; }
        public SequenceDal sequenceDal { get; set; }

        /// <summary>
        /// 根据Key获取Sequence的值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public int QuerySequnenceByKey(string key)
        {
            return sequenceDal.QuerySequnenceByKey(key);
        }

        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool CreateSequence(string key)
        {
            return sequenceDal.CreateSequence(key);
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="sequenceKey"></param>
        /// <returns></returns>
        public bool UpdateVal(string sequenceKey)
        {
            return sequenceDal.UpdateVal( sequenceKey);
        }

        /// <summary>
        /// 获取筛查编号
        /// 原程序 :ScreeningServiceImpl-> private String getSCNum()
        /// </summary>
        /// <returns></returns>
        public String GetSCNum()
        {
            string currentYear = DateTime.Now.ToString("yy");
            return currentYear + this.GetSequece("SCNUM");
        }


        /// <summary>
        /// 默认长度6
        /// 原程序 :SequenceServiceImpl-> public String getSequece(String key)
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetSequece(string key)
        {
            return GetSequence(key, 6);
        }

        /// <summary>
        /// 原程序 :SequenceServiceImpl-> public String getSequence(String key,int length)
        /// </summary>
        /// <param name="key"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public string GetSequence(string key, int length)
        {
            int val = 1;
            bool result = this.UpdateVal(key);
            if (result)
            {
                val = this.QuerySequnenceByKey(key);
            }
            else
            {
                this.CreateSequence(key);
            }
            string sVal = val.ToString();
            //补0
            if (sVal.Length < length)
            {

                sVal = sVal.PadLeft(6, '0'); 
            }
            else if (sVal.Length > length)
            {
                sVal = sVal.Substring(sVal.Length - length);
            }
            return sVal;
        }
    }
}
